<template>
  <section>
    <div class="container">
      <div class="container-title">查询条件</div>
      <div class="container-body pd">
        <el-form
          label-position="right"
          label-width="120px"
          :model="searchForm"
          ref="searchForm"
          class="demo-form-inline"
        >
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="商品名称：" size="small" prop="name">
                <el-input
                  v-model="searchForm.name"
                  type="text"
                  placeholder="请输入商品名称"
                  prefix-icon="el-icon-search"
                  size="small"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否上架：" size="small" prop="isUpper">
                <el-select
                  v-model="searchForm.isUpper"
                  clearable
                  placeholder="请选择"
                  size="small"
                >
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row type="flex" justify="center">
            <el-button
              class="is-tableBtn"
              size="small"
              @click="clearForm('searchForm')"
              >清空</el-button
            >
            <el-button
              class="is-tableBtn"
              type="primary"
              size="small"
              @click="onSearch(searchForm)"
              >查询</el-button
            >
          </el-row>
        </el-form>
      </div>
    </div>
    <div class="container">
      <div class="container-title">商品列表</div>
      <div class="container-body pd">
        <el-button
          type="primary"
          @click="createGoodsPop = true"
          class="btnAddGoods"
          size="small"
        >
          新增商品</el-button
        >
        <el-table
          :data="tableData"
          border
          style="width: 100%"
          size="small"
          v-loading="loading"
        >
          <el-table-column prop="name" label="商品名称" align="center">
          </el-table-column>

          <el-table-column prop="price" label="价格" align="center">
          </el-table-column>
          <el-table-column prop="salesNum" label="数量" align="center">
          </el-table-column>

          <el-table-column
            prop="thumbnailImgUrl"
            label="缩略图"
            align="center"
            width="150"
          >
            <template slot-scope="scope">
              <el-image
                style="width: auto; height: 40px"
                :src="scope.row.thumbnailImgUrl"
                :preview-src-list="[scope.row.thumbnailImgUrl]"
              >
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="isUpper" label="是否上架" align="center">
            <template slot-scope="scope">
              {{ scope.row.isUpper ? "是" : "否" }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center">
          </el-table-column>
          <el-table-column label="操作" align="center" width="150">
            <template slot-scope="scope">
              <el-button
                class="btnwarning"
                type="warning"
                size="mini"
                @click="handleEdit(scope.$index, scope.row)"
                >编辑</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="pageBox">
          <el-pagination
            background
            layout="prev, pager, next"
            :total="total"
            @current-change="currentPage"
          >
          </el-pagination>
          <div class="clear"></div>
        </div>
      </div>
    </div>
    <!-- 新增商品弹窗 -->
    <el-drawer
      :visible.sync="createGoodsPop"
      :append-to-body="true"
      custom-class="form-drawer"
      @close="close()"
    >
      <div class="drawer" slot="title">
        {{ editID ? "编辑商品" : "新增商品" }}
      </div>
      <div class="drawerContainer">
        <div class="drawerFormBox">
          <el-form
            :model="newGoodsForm"
            :rules="newGoodsRule"
            ref="newGoodsForm"
            label-width="160px"
            class="demo-newGoodsForm"
            size="small"
          >
            <el-form-item label="商品分类" prop="classifyId">
              <el-select
                v-model="newGoodsForm.classifyId"
                clearable
                placeholder="请选择"
              >
                <el-option
                  v-for="item in goodsClassList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="newGoodsForm.name"></el-input>
            </el-form-item>
            <el-form-item label="缩略图" prop="ThumbnailImgUrl">
              <uploadImg
                :showImgUrl="newGoodsForm.thumbnailImgUrl"
                @setImg="setImg"
                fiedName="thumbnailImgUrl"
              />
            </el-form-item>

            <el-form-item label="详情图" prop="detailsImgUrl">
              <uploadImg
                :showImgUrl="newGoodsForm.detailsImgUrl"
                @setImg="setImg"
                fiedName="detailsImgUrl"
              />
            </el-form-item>
            <el-form-item label="商品圆形图" prop="circularImgUrl">
              <uploadImg
                :showImgUrl="newGoodsForm.circularImgUrl"
                @setImg="setImg"
                fiedName="circularImgUrl"
              />
            </el-form-item>
            <el-form-item label="卡封面图" prop="cardImgUrl">
              <uploadImg
                :showImgUrl="newGoodsForm.cardImgUrl"
                @setImg="setImg"
                fiedName="cardImgUrl"
              />
            </el-form-item>

            <el-form-item label="价格" prop="price">
              <el-input v-model="newGoodsForm.price"></el-input>
            </el-form-item>
            <el-form-item label="规格" prop="specs">
              <el-input v-model="newGoodsForm.specs"></el-input>
            </el-form-item>
            <el-form-item label="特点" prop="characteristic">
              <el-input
                v-model="newGoodsForm.characteristic"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }"
              ></el-input>
            </el-form-item>
            <el-form-item label="营养价值" prop="worth">
              <el-input
                v-model="newGoodsForm.worth"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }"
              ></el-input>
            </el-form-item>
            <el-form-item label="适用场景" prop="scene">
              <el-input
                v-model="newGoodsForm.scene"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }"
              ></el-input>
            </el-form-item>

            <el-form-item label="是否上架" prop="isUpper">
              <el-switch
                v-model="newGoodsForm.isUpper"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </el-form-item>
            <el-form-item label="商品备注" prop="remarks">
              <el-input
                v-model="newGoodsForm.remarks"
                type="textarea"
                :autosize="{ minRows: 2, maxRows: 4 }"
              ></el-input>
            </el-form-item>

            <el-form-item label="数量" prop="salesNum">
              <el-input v-model.number="newGoodsForm.salesNum"></el-input>
            </el-form-item>

            <el-form-item label="JD ECLP主商品名称：" prop="eclpGoodsNo">
              <el-select
                v-model="newGoodsForm.eclpGoodsNo"
                clearable
                @change="changeJDName"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in JDClassList"
                  :key="item.goodsNo"
                  :label="item.goodsName"
                  :value="item.goodsNo"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="drawerBtnBox">
          <el-button @click="resetFormESC('newGoodsForm')" size="small"
            >取 消</el-button
          >
          <el-button
            type="primary"
            @click="
              editID
                ? updategoodsForm('newGoodsForm')
                : resetForm('newGoodsForm')
            "
            size="small"
            >确 定</el-button
          >
        </div>
      </div>
    </el-drawer>
  </section>
</template>
<script>
import uploadImg from "@/components/uploadImg";
export default {
  data() {
    var isnumber = (rule, value, callback) => {
      if (!value) {
        callback();
      } else {
        var reg = /^-?\d{1,16}(?:\.\d{1,2})?$/; //小数点左边最高16位，小数点右边最多4位
        if (reg.test(value)) {
          callback();
        } else {
          callback(new Error("输入正确的价格"));
        }
      }
    };
    return {
      editID: "",
      page: 1,
      total: 0,
      options: [
        {
          value: false,
          label: "否",
        },
        {
          value: true,
          label: "是",
        },
      ],

      createGoodsPop: false, // 商品创建弹窗是否展示
      searchForm: {
        goodsName: "",
        goodsCode: "",
        goodsType: "",
      },
      newGoodsForm: {
        name: "",
        price: "",
        remarks: "",
        salesNum: 0,
        specs: "",
        characteristic: "",
        worth: "",
        scene: "",
        eclpGoodsNo: "",
        eclpGoodsName: "",
        thumbnailImgUrl: "", // 商品图片
        detailsImgUrl: "", // 商品详情图片
        circularImgUrl: "",
        cardImgUrl: "",
      },
      newGoodsRule: {
        classifyId: [
          { required: true, message: "请选择分类", trigger: "blur" },
        ],

        name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        price: [{ required: true, validator: isnumber, trigger: "blur" }],
        salesNum: [{ type: "number", message: "数量必须为数字值" }],
      },
      tableData: [],
      goodsClassList: [], // 商品分类
      JDClassList: [], // 京东商品分类
      loading: true,
    };
  },
  created() {
    this.onSearch(this.searchForm);
    this.GetTbClassifyDropList(); // 获取商品分类
    this.GetEclpGoodsQueryGoodsInfo();
  },
  components: {
    uploadImg,
  },
  methods: {
    changeJDName(e) {
      console.log(e);
    },
    setImg(data) {
      this.newGoodsForm[data.fiedName] = data.imageUrl;
    },
    clearForm(formName) {
      // 清空筛选
      this.$refs[formName].resetFields();
    },
    async resetForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 请求案例
          this.editID = "";
          let res = await this.$store.dispatch("postTbGoods", {
            Name: this[formName].name,
            ThumbnailImgUrl: this[formName].thumbnailImgUrl,
            DetailsImgUrl: this[formName].detailsImgUrl,
            CircularImgUrl: this[formName].circularImgUrl,
            CardImgUrl: this[formName].cardImgUrl,
            Price: +this[formName].price,
            IsUpper: this[formName].isUpper,
            SalesNum: +this[formName].salesNum,
            Remarks: this[formName].remarks,
            EclpGoodsNo: this[formName].eclpGoodsNo,
            EclpGoodsName: this[formName].eclpGoodsName,
            ClassifyId: this[formName].classifyId,
            Specs: this[formName].specs,
            Characteristic: this[formName].characteristic,
            Worth: this[formName].worth,
            Scene: this[formName].scene,
          });
          if (res.success) {
            this.onSearch(this.searchForm);
            this.resetFormESC("newGoodsForm");
            this.$message({
              message: "新增成功",
              type: "success",
            });
          } else {
            this.$message.error(res.ErrorMessage || "网络异常");
          }
        } else {
          return false;
        }
      });
    },
    currentPage(page) {
      this.page = page;
      this.onSearch(this.searchForm);
    },

    async onSearch(searchForm) {
      this.loading = true;
      let skip = (this.page - 1) * 10;
      // 请求案例
      let res = await this.$store.dispatch("getTbGoodsList", {
        name: searchForm.name,
        isUpper: searchForm.isUpper,
        skip,
      });
      if (res.success) {
        this.tableData = res.data.itmes || [];
        this.total = res.data.totalCount;
      } else {
        this.$message.error(res.ErrorMessage || "网络异常");
      }
      this.loading = false;
    },
    async GetTbClassifyDropList() {
      // 商品分类
      let res = await this.$store.dispatch("GetTbClassifyDropList", {});
      if (res.success) {
        this.goodsClassList = res.data || [];
      } else {
        this.$message.error(res.ErrorMessage || "网络异常");
      }
    },

    async GetEclpGoodsQueryGoodsInfo() {
      let res = await this.$store.dispatch("GetEclpGoodsQueryGoodsInfo", {});
      if (res.success) {
        this.JDClassList = res.data || [];
      } else {
        this.$message.error(res.ErrorMessage || "网络异常");
      }
    },

    onSubmit() {},
    getGoodsImg(data) {
      this.getImg(data.file, "thumbnailImgUrl");
    },
    getGoodsDetailImg(data) {
      this.getImg(data.file, "detailsImgUrl");
    },
    getcircularImgUrl(data) {
      this.getImg(data.file, "circularImgUrl");
    },
    getImg(file, fileNmae) {
      let reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = async (e) => {
        // file转base64
        let base64 = e.target.result;
        this.newGoodsForm[`${fileNmae}`] = base64;
      };
    },
    resetFormESC(formName) {
      // 充值表单
      this.createGoodsPop = false;
      this.newGoodsForm.thumbnailImgUrl = "";
      this.$refs[formName].resetFields();
    },
    beforeAvatarUpload(file) {
      console.log(file);
      let reg = /^(\s|\S)+.(png|jpg|gif|jpeg|webp)$/;
      const imgType = reg.test(file.type);
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!imgType) {
        this.$message.error("请上传正确图片");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M && imgType;
    },
    close() {
      this.editID = "";
      this.resetFormESC("newGoodsForm");
    },

    async handleEdit(index, row) {
      let res = await this.$store.dispatch("GetTbGoods", {
        id: row.id,
      });
      if (res.success) {
        this.newGoodsForm = res.data || [];
        console.log(this.newGoodsForm);
      } else {
        this.$message.error(res.ErrorMessage || "网络异常");
      }
      this.editID = row.id;
      this.createGoodsPop = true;
    },

    async updategoodsForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          // 编辑案例
          let res = await this.$store.dispatch("PutTbGoods", {
            Id: this.editID,
            Name: this[formName].name,
            ThumbnailImgUrl: this[formName].thumbnailImgUrl,
            DetailsImgUrl: this[formName].detailsImgUrl,
            CircularImgUrl: this[formName].circularImgUrl,
            CardImgUrl: this[formName].cardImgUrl,
            Price: +this[formName].price,
            IsUpper: this[formName].isUpper,
            SalesNum: +this[formName].salesNum,
            Remarks: this[formName].remarks,
            EclpGoodsNo: this[formName].eclpGoodsNo,
            EclpGoodsName: this[formName].eclpGoodsName,
            Specs: this[formName].specs,
            Characteristic: this[formName].characteristic,
            Worth: this[formName].worth,
            Scene: this[formName].scene,
            ClassifyId: this[formName].classifyId,
          });
          if (res.success) {
            this.onSearch(this.searchForm);
            this.resetFormESC("newGoodsForm");
            this.$message({
              message: "修改成功",
              type: "success",
            });
          } else {
            this.$message.error(res.ErrorMessage || "网络异常");
          }
          this.editID = "";
        } else {
          return false;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/varibles.scss";
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  border: 1px dashed #8c939d;
  border-radius: 6px;
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.btnAddGoods {
  margin-bottom: $btnHeight;
}

.btnwarning {
  color: $btnwarning;
}

.pageBox {
  padding-top: 10px;
  clear: both;
  .el-pagination {
    float: right;
  }

  .clear {
    clear: both;
  }
}
</style>
